//
//  MTEmailShow6ViewController.m
//  YuchBox
//
//  Created by Ivan on 11-11-4.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "MTEmailShow6ViewController.h"
#import "YuchBoxAppDelegate.h"
#import "IvanSqliteDB.h"
#import "LayoutParam.h"
#import "QuartzCore/QuartzCore.h"
#import "DataSource.h"

@interface UIImage (scale)
- (UIImage *)scaleToSize:(CGSize)size;
@end

@implementation UIImage (scale)

- (UIImage *)scaleToSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return scaledImage;
}
@end


@implementation MTEmailShow6ViewController
//@synthesize showTableView = _showTableView;

@synthesize currentDelegate    = _currentDelegate;
enum CELL_TAG_DEFINDE
{
    TITLE_LABEL_TAG         = 100,
    CONTENT_LABEL_TAG,
    ACTIVITY_TAG,
    CONTENT_HTML_TAG,
    
    ATTACH_VIEW_TAG         = 1000,
    ATTACH_VIEW_ICON_TAG,
    ATTACH_VIEW_LABEL_TAG,
    ATTACH_VIEW_BUTTON_TAG,
};

// cell height
#define CH_NOSET  -1
#define CH_HIDDEN  0

//#define CONTENT_LABEL_TAG   100
//#define ACTIVITY_TAG        101
//#define CONTENT_HTML_TAG    102

#define CELL_NUMBER         7

#define CELL_SUBJECT        0
#define CELL_FROM           1
#define CELL_SENDTIME       2
#define CELL_TO             3
#define CELL_ATTACHMENT     4
#define CELL_CONTENT        5
#define CELL_CONTENT_HTML   6


#define CELL_TITLE_MAX_LENGTH   15
typedef struct cell_s {
    bool    is_hide;
    bool    hide_default;
    
    bool    is_flod;
    bool    flod_default;
    
    float   height_default;
    float   height_current;
    
    char    title[CELL_TITLE_MAX_LENGTH];
} cell_t;

static cell_t CELL[CELL_NUMBER] = { {NO, NO, NO, YES, 40, 0, "标   题："},
                                    {NO, NO, NO, YES, 40, 0, "发件人："},
                                    {NO, NO, NO, YES, 40, 0, "时   间："},
                                    {NO, NO, NO, YES, 40, 0, "收件人："},
                                    {NO, NO, NO, YES, 40, 0, "附   件："},
                                    {NO, NO, NO, YES, 40, 0, "内   容："},
                                    {NO, NO, NO, YES, 100, 0, " HTML："},};

#define CELL_SET_DEFAULT    for (int i = 0; i < CELL_NUMBER; i++) {\
                                CELL[i].height_current = 0;\
                                CELL[i].is_hide = CELL[i].hide_default;\
                                CELL[i].is_flod = CELL[i].flod_default;\
                            }

static const float max_label_width  = 320;
static const float max_label_height = 4000;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _isSameEmail = NO;
    }
    return self;
}

- (void)dealloc
{
    [_currentEmail release];
    _currentEmail = nil;
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)loadEmail:(Email *)email
{
    if (nil == _currentEmail || email.uid != _currentEmail.uid) {
        [_currentEmail release];
        _currentEmail = email;
        [email retain];
        _isSameEmail = NO;
        
        _currentEmailIndex = [_currentDelegate.emails indexOfObject:_currentEmail];
    } else {
        _isSameEmail = YES;
    }
}

- (void)prevEmail
{
    NSInteger prevEmailIndex = _currentEmailIndex - 1;
    if (prevEmailIndex < 0) {
        return;
    }
    
    Email *email = [_currentDelegate.emails objectAtIndex:prevEmailIndex];
    [self loadEmail:email];
    [self viewWillAppear:NO];
    [self viewDidAppear:NO];
}

- (void)nextEmail
{
    NSInteger nextEmailIndex = _currentEmailIndex + 1;
    if (nextEmailIndex == _currentDelegate.emailsTotalCount) {
        return;
    }
    
    if (nextEmailIndex == _currentDelegate.emails.count) {
        [_currentDelegate loadMoreEmail];
    }
    
    Email *email = [_currentDelegate.emails objectAtIndex:nextEmailIndex];
    [self loadEmail:email];
    [self viewWillAppear:NO];
    [self viewDidAppear:NO];
}

- (void)setBarItems
{
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(150, 0, 300, 40)];
//    titleItemsView.alpha = 1.0f;
//    titleItemsView.backgroundColor = [UIColor greenColor];
    
    UIButton *prevButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [titleView addSubview:prevButton];
    prevButton.frame = CGRectMake(169, 7, 26, 26);
    [prevButton setBackgroundImage:[UIImage imageNamed:@"arrow_left.png"] forState:UIControlStateNormal];
    [prevButton addTarget:self action:@selector(prevEmail) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [titleView addSubview:nextButton];
    nextButton.frame = CGRectMake(212, 7, 26, 26);
    [nextButton setBackgroundImage:[UIImage imageNamed:@"arrow_right.png"] forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(nextEmail) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(77, 0, 60, 40)];
    label.backgroundColor = [UIColor clearColor];
    
    label.text = [NSString stringWithFormat:@"%d/%d", _currentEmailIndex + 1, _currentDelegate.emailsTotalCount];
    label.font = [UIFont boldSystemFontOfSize:16];
    label.textColor = [UIColor whiteColor];
    [titleView addSubview:label];
    [label release];
    
//    [button release];
    [self.navigationItem setTitleView:titleView];
    [titleView release];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _attachmentReaderViewController = [[AttachmentReaderViewController alloc] init];
    CELL_SET_DEFAULT;
    // TODO put the loading icon
    _contentHtmlView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, CELL[CELL_CONTENT_HTML].height_default)];
    [_contentHtmlView setDelegate:self];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [_attachmentReaderViewController release];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [_contentHtmlView release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];   
    [self.navigationController setDelegate:self];

    [self setBarItems];
    if (_isSameEmail) {
        return;
    }
    
    CELL_SET_DEFAULT;
    
    // hide the none content cell
    if (0 == [UTIL_TRIM(_currentEmail.content) length]) {
        CELL[CELL_CONTENT].is_hide = YES;
    }
    
    if (0 == [_currentEmail.attachmentArray count]) {
        CELL[CELL_ATTACHMENT].is_hide = YES;
    }
        
    //[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:CELL_SUBJECT inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    [self.tableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[YuchBoxAppDelegate shareStateViewer] setTemporaryHide:NO delegate:self];

    if (EMAIL_STATUS_RECV_UNREAD == _currentEmail.status || EMAIL_STATUS_RECV_ATTACH_UNREAD == _currentEmail.status) {
        [_currentDelegate eventInvoke:DSEventOpEmailRead info:_currentEmail];
    }
    
}

- (void)initRowView:(UIView *)view title:(NSString *)title indexPath:(NSIndexPath *)indexPath
{
    view.backgroundColor = [UIColor grayColor];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 70, CELL[indexPath.row].height_default)];
    titleLabel.text             = title;
    titleLabel.textColor        = [UIColor darkGrayColor];
    titleLabel.font             = [UIFont systemFontOfSize:14];
    titleLabel.textAlignment    = UITextAlignmentRight;
    titleLabel.tag              = TITLE_LABEL_TAG;
    [view addSubview:titleLabel];
    [titleLabel release];
    
    UILabel *contentLabel   = [[UILabel alloc] initWithFrame:CGRectMake(70, 0, 250, CELL[indexPath.row].height_default)];
    contentLabel.font           = [UIFont systemFontOfSize:14];
    contentLabel.textAlignment  = UITextAlignmentLeft;
    contentLabel.tag            = CONTENT_LABEL_TAG;
    [view addSubview:contentLabel];
    [contentLabel release];
}

- (void)resetLabelHeight:(UILabel *)contentLabel indexPath:(NSIndexPath *)indexPath isFold:(Boolean)isFold
{    
    //    UILabel *contentLabel   =   (UILabel *)[view viewWithTag:CONTENT_LABEL_TAG];
    NSInteger numberOfLines = 0;
    CGFloat labelHeight     = 0.0f;
    
    // computing the text height
    if (0 == CELL[indexPath.row].height_current) {         
        CGSize size = [contentLabel.text sizeWithFont:contentLabel.font constrainedToSize:CGSizeMake(contentLabel.frame.size.width, max_label_height) lineBreakMode:UILineBreakModeClip];
        size.height += 20;
        CELL[indexPath.row].height_current = MAX(size.height, CELL[indexPath.row].height_default);
    }
    
    //if (!CELL[indexPath.row].is_hide) {
        if (isFold){
            numberOfLines = 1;
            labelHeight = CELL[indexPath.row].height_default;
        } else {
            numberOfLines = 0;
            labelHeight =  CELL[indexPath.row].height_current;
        }
//    }
    
    contentLabel.numberOfLines = numberOfLines;
    contentLabel.frame = CGRectMake(contentLabel.frame.origin.x, 
                                    contentLabel.frame.origin.y,
                                    contentLabel.frame.size.width,
                                    labelHeight);
}

- (void)setContentLabelText:(UIView *)view content:(NSString *)content indexPath:(NSIndexPath *)indexPath
{
    UILabel *contentLabel = (UILabel *)[view viewWithTag:CONTENT_LABEL_TAG];
    contentLabel.text = content;
    
    // set the label height
    
    [self resetLabelHeight:contentLabel indexPath:indexPath isFold:CELL[indexPath.row].is_flod];
}

- (void)setContentLabelText:(UIView *)view content:(NSString *)content font:(UIFont *)font indexPath:(NSIndexPath *)indexPath
{
    UILabel *contentLabel = (UILabel *)[view viewWithTag:CONTENT_LABEL_TAG];
    contentLabel.font = font;
    
    [self setContentLabelText:view content:content indexPath:indexPath];
}


- (void)showAttachmentContent:(UIButton *)button
{
   [_attachmentReaderViewController loadAttachment:[_currentEmail.attachmentArray objectAtIndex:button.tag]];
//    UIViewController *viewController = [YuchBoxAppDelegate shareAppDelegate].rootToolBarViewController;
    [self.navigationController pushViewController:_attachmentReaderViewController animated:YES];
//    [self.navigationController pushViewController:tmp animated:YES];
}

- (void)setAttachmentView:(UIView *)view attachmentIndex:(NSInteger)attachmentIndex
{
#define ATTACH_VIEW_X               15.0f
#define ATTACH_VIEW_Y               15.0f
#define ATTACH_VIEW_WIDTH           285.0f
#define ATTACH_VIEW_HEIGHT          40.f
#define ATTACH_VIEW_BOTTOM_MARGIN   15.0f
#define MAIN_BACKGROUD_COLOR    [UIColor colorWithRed:192.0/255.0 green:192.0/255.0 blue:192.0/255.0 alpha:1.0]
    
    UITableViewCell *fileCell = [[UITableViewCell alloc] init];
    CALayer *layer = fileCell.layer;
    CGFloat currentY = ATTACH_VIEW_Y + (CGFloat)((ATTACH_VIEW_HEIGHT + ATTACH_VIEW_BOTTOM_MARGIN) * attachmentIndex);
    layer.frame = CGRectMake(ATTACH_VIEW_X, currentY, ATTACH_VIEW_WIDTH, ATTACH_VIEW_HEIGHT);

    layer.borderColor = MAIN_BACKGROUD_COLOR.CGColor;
    layer.borderWidth = 2;
    layer.cornerRadius = 5.0;    
    fileCell.backgroundColor = MAIN_BACKGROUD_COLOR;

#define ATTACH_VIEW_ICON_X          12.0f
#define ATTACH_VIEW_ICON_Y          5.0f
#define ATTACH_VIEW_ICON_WIDTH      32.0f
#define ATTACH_VIEW_ICON_HEIGHT     32.0f
  
#define ATTACH_VIEW_LABEL_X         (ATTACH_VIEW_ICON_X + ATTACH_VIEW_ICON_WIDTH + 12.0f)
#define ATTACH_VIEW_LABEL_Y         ATTACH_VIEW_ICON_Y
#define ATTACH_VIEW_LABEL_WIDTH     180.f
#define ATTACH_VIEW_LABEL_HEIGHT    ATTACH_VIEW_ICON_HEIGHT
    
#define ATTACH_VIEW_BUTTON_X        (ATTACH_VIEW_LABEL_X + ATTACH_VIEW_LABEL_WIDTH + 10.0f)
#define ATTACH_VIEW_BUTTON_Y        ATTACH_VIEW_ICON_Y
#define ATTACH_VIEW_BUTTON_WIDTH    30.0f
#define ATTACH_VIEW_BUTTON_HEIGHT   ATTACH_VIEW_ICON_HEIGHT
    
    UIImageView *fileTypeIcon = [[UIImageView alloc] initWithFrame:CGRectMake(ATTACH_VIEW_ICON_X, 
                                                                              ATTACH_VIEW_ICON_Y, 
                                                                              ATTACH_VIEW_ICON_WIDTH, 
                                                                              ATTACH_VIEW_ICON_HEIGHT)];
    
    [fileTypeIcon setImage:[UIImage imageNamed:@"file_type_txt.png"]];// scaleToSize:CGSizeMake(16.0f, 16.0f)]]
    [fileTypeIcon setTag:ATTACH_VIEW_ICON_TAG];
    [fileCell addSubview:fileTypeIcon];  
    [fileTypeIcon release];
    
    UILabel *fileNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(ATTACH_VIEW_LABEL_X, 
                                                                       ATTACH_VIEW_LABEL_Y,
                                                                       ATTACH_VIEW_LABEL_WIDTH, 
                                                                       ATTACH_VIEW_LABEL_HEIGHT)];

    fileNameLabel.font      = [UIFont boldSystemFontOfSize:14];
    fileNameLabel.textColor = [UIColor whiteColor];
    fileNameLabel.backgroundColor = MAIN_BACKGROUD_COLOR; 
    [fileNameLabel setTag:ATTACH_VIEW_LABEL_TAG];
    [fileCell addSubview:fileNameLabel];
    [fileNameLabel release];
    
    UIButton *fileViewButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    
    fileViewButton.frame = CGRectMake(ATTACH_VIEW_BUTTON_X, 
                                      ATTACH_VIEW_BUTTON_Y, 
                                      ATTACH_VIEW_BUTTON_WIDTH, 
                                      ATTACH_VIEW_BUTTON_HEIGHT);
    
    [fileViewButton setTag:attachmentIndex];
    [fileViewButton addTarget:self action:@selector(showAttachmentContent:) forControlEvents:UIControlEventTouchUpInside];
    [fileCell addSubview:fileViewButton];
    
    [fileCell setTag:(ATTACH_VIEW_TAG * attachmentIndex)];
    [view addSubview:fileCell];
    [fileCell release];    
}

#pragma mark -
#pragma UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return CELL_NUMBER;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"heightForRowAtIndexPath %d %f %f", indexPath.row, CELL[indexPath.row].height_default, CELL[indexPath.row].height_current);
    CGFloat height = CELL[indexPath.row].is_flod ? CELL[indexPath.row].height_default : CELL[indexPath.row].height_current;
    //NSLog(@"heightForRowAtIndexPath %d %f", indexPath.row, height);
    return height;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 10.0f;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    return 10.0f;
//}


- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"accessoryButtonTappedForRowWithIndexPath");
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"commitEditingStyle");
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
//    NSLog(@"select row %d", indexPath.row);
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (nil != cell) {    
        switch (indexPath.row) {
            case CELL_SUBJECT:
            case CELL_FROM:
            case CELL_TO: 
            case CELL_ATTACHMENT:
            case CELL_CONTENT:{
                UITableViewRowAnimation rowAnimation;
                if (CELL[indexPath.row].is_flod) {
                    // expend
                    CELL[indexPath.row].is_flod = NO;
                    rowAnimation = UITableViewRowAnimationFade;
                } else {
                    CELL[indexPath.row].is_flod = YES;
                    rowAnimation = UITableViewRowAnimationFade;
                }
                [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:rowAnimation];
                break;
            }
                
            default:
                break;
        }
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *MyIdentifier = [NSString stringWithFormat:@"CELL_%d_%@",indexPath.row, CELL[indexPath.row].is_flod ? @"flod" : @"expend"];
    NSLog(@"%@", MyIdentifier);
	// Try to retrieve from the table view a now-unused cell with the given identifier.
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    
    if (nil == cell) {
        NSLog(@"CELL create");
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
        switch (indexPath.row) {
            case CELL_SUBJECT: 
            case CELL_FROM:
            case CELL_SENDTIME:
            case CELL_TO: {
                [self initRowView:cell title:[NSString stringWithUTF8String:CELL[indexPath.row].title] indexPath:indexPath];
                break;
            }
            case CELL_ATTACHMENT: {
            
                if (CELL[CELL_ATTACHMENT].is_flod) {
                    [self initRowView:cell title:[NSString stringWithUTF8String:CELL[indexPath.row].title] indexPath:indexPath];
                } else {
                    int i = 0;
                    for (Attachment *attach in _currentEmail.attachmentArray) {
                        [self setAttachmentView:cell attachmentIndex:i++];
                    }
                }
                
                break;
            }
            case CELL_CONTENT: {
                UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, DEVICE_WIDTH - 10, CELL[CELL_CONTENT].height_default)];
                //[cell addSubview:label];

                contentLabel.font = [UIFont systemFontOfSize:14];
                contentLabel.textAlignment = UITextAlignmentLeft;
                contentLabel.tag  = CONTENT_LABEL_TAG;
                [cell addSubview:contentLabel];
                [contentLabel release];
                break;
            }
            case CELL_CONTENT_HTML: {
                // two cell are diffrent in `if` and `else` block
                if (CELL[CELL_CONTENT_HTML].is_flod){
                    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                    activityIndicator.frame = CGRectMake(140, 10, 50, 50);
                    [cell addSubview:activityIndicator];
                    [activityIndicator setTag:ACTIVITY_TAG];
                    [activityIndicator release];
//                    cell.backgroundColor = [UIColor whiteColor];
                
                // TODO put the open button here
                } else {
                    [cell addSubview:_contentHtmlView];
                }
                break;
            }
        }

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    switch (indexPath.row) {
        case CELL_SUBJECT:
            [self setContentLabelText:cell content:_currentEmail.subject font:[UIFont boldSystemFontOfSize:14] indexPath:indexPath];
            break;
        case CELL_FROM:
            [self setContentLabelText:cell content:_currentEmail.fromString indexPath:indexPath];
            break;
        case CELL_SENDTIME: {
            NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
            [dateformatter setDateFormat:@"yyyy年MM月dd日 HH:mm:ss"];
            [self setContentLabelText:cell content:[dateformatter stringFromDate:_currentEmail.sendDate] indexPath:indexPath];
            [dateformatter release];
            break;
        }
        case CELL_TO:
            [self setContentLabelText:cell content:_currentEmail.toString indexPath:indexPath];
            break;
        case CELL_ATTACHMENT: {
            
            if (CELL[CELL_ATTACHMENT].is_flod) {
                NSUInteger attachmentsCount = [_currentEmail.attachmentArray count];
                NSString *appendString;
                if (0 == attachmentsCount) {
                    appendString = @"";
                } else {
                    Attachment *firstAttach = [_currentEmail.attachmentArray objectAtIndex:0];
                    appendString = [NSString stringWithFormat:@"(%@)", firstAttach.realName];
                }
                [self setContentLabelText:cell content:[NSString stringWithFormat:@"%u个附件%@", attachmentsCount, appendString] indexPath:indexPath];
                // compute height
                CELL[CELL_ATTACHMENT].height_current = ATTACH_VIEW_Y + (ATTACH_VIEW_HEIGHT + ATTACH_VIEW_BOTTOM_MARGIN) * attachmentsCount;
                
            } else {
                int i = 0;
                for (Attachment *attach in _currentEmail.attachmentArray) {
                    //[self setAttachmentView:cell attachmentIndex:i++];
                    UITableViewCell *attachView = (UITableViewCell *)[cell viewWithTag:(ATTACH_VIEW_TAG * i)];
                    attachView.hidden = NO;
                    if (nil == attachView) {
                        // add new attachment view(cell)
                        [self setAttachmentView:cell attachmentIndex:i];
                        attachView = (UITableViewCell *)[cell viewWithTag:(ATTACH_VIEW_TAG * i)];
                    }
                    
                    UILabel * fileNameLabel = (UILabel *)[attachView viewWithTag:ATTACH_VIEW_LABEL_TAG];
                    NSString *fileSize;
                    if (attach.attachmentSize < 1024) {
                        fileSize = [NSString stringWithFormat:@"%dB", attach.attachmentSize];
                    } else if (attach.attachmentSize < 1024*1024) {
                        fileSize = [NSString stringWithFormat:@"%0.2fKB", (attach.attachmentSize / 1024.0)];
                    } else {
                        fileSize = [NSString stringWithFormat:@"%0.2fMB", (attach.attachmentSize / (1024.0 * 1024.0))];
                    }
                    
                    fileNameLabel.text = [NSString stringWithFormat:@"%@（%@）", attach.realName, fileSize];
                    
                    i++;
                }
                
                // hidden the extra cell
                UITableViewCell *attachView = nil;//(UITableViewCell *)[cell viewWithTag:(ATTACH_VIEW_TAG * i)];
                do {
                    attachView = (UITableViewCell *)[cell viewWithTag:(ATTACH_VIEW_TAG * i++)];
                    if (attachView != nil) {
                        attachView.hidden = YES;
                    } else {
                        break;
                    }
                } while (TRUE);
                   
            }
//            NSUInteger attachmentsCount = [_currentEmail.attachmentArray count];
            break;
        }
        case CELL_CONTENT: {
            [self setContentLabelText:cell content:_currentEmail.content indexPath:indexPath];
            break;
        }
        case CELL_CONTENT_HTML: {
            UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView *)[cell viewWithTag:ACTIVITY_TAG];
            if (CELL[CELL_CONTENT_HTML].is_flod){
                [_contentHtmlView stopLoading];
                [activityIndicator startAnimating];
                [cell addSubview:activityIndicator];
                
                [_contentHtmlView loadHTMLString:_currentEmail.contentHtml baseURL:nil];
            } else {
                [activityIndicator stopAnimating];
            }
            break;
        }
    }
    
    if (CELL[indexPath.row].is_hide) {
        cell.hidden = YES;
    }
    
    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	return cell;
}

#pragma mark -
#pragma UIWebViewDelegate

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //if (webView == _contentHtmlView) {
    NSString *height = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"EmailContentHtml\").offsetHeight"];
    NSString *width = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"EmailContentHtml\").offsetWidth"];
    CGSize readContentSize = CGSizeMake([width floatValue], [height floatValue] + 30.0);
    
    webView.frame = CGRectMake(0, 0, DEVICE_WIDTH, readContentSize.height);
    
    
    if ([[webView subviews] count] > 0) {
        UIScrollView *scrollView = [[webView subviews] lastObject];
        //scrollView.contentSize = CGSizeMake(readContentSize.width, readContentSize.height);
        CGFloat zoomScale = DEVICE_WIDTH / readContentSize.width;
        NSLog(@"webViewDidFinishLoad, readContentSizeHeight:%f readContentSizeWidth:%f zoomScale:%f", readContentSize.height, readContentSize.width, zoomScale);
        scrollView.minimumZoomScale = 0.5f;
        //scrollView.zoomScale = MAX(zoomScale, scrollView.minimumZoomScale);
    }
    
    CELL[CELL_CONTENT_HTML].is_flod         = NO;
    CELL[CELL_CONTENT_HTML].height_current  = readContentSize.height;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:CELL_CONTENT_HTML inSection:0];

    // WARNING when reload , there are two cell, one for before reaload, two for after reload
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
    //}
}

#pragma mark -
#pragma StateViewerDelegate

- (void)stateViewerSetup:(StateViewer *)stateViewer
{
//    [self.navigationController.navigationBar addSubview:stateViewer];
}

- (void)stateViewerUnsetup:(StateViewer *)stateViewer
{
//    [stateViewer removeFromSuperview];
}

#pragma mark -
#pragma NavigationControllerDelegate

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [[YuchBoxAppDelegate shareStateViewer] setTemporaryHide:NO delegate:nil];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [[YuchBoxAppDelegate shareStateViewer] setTemporaryHide:YES delegate:nil];
}
@end

//
// class
//

@implementation AttachmentReaderViewController

- (id)initWithAttachment:(Attachment *)attachment
{
    self = [super init];
    if (self) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
        textLabel.text = @"12312312312";
        [_scrollView addSubview:textLabel];
        [textLabel release];
        
        [self.view addSubview:_scrollView];
    }
    return self;
}

#define ATTACH_READER_LABEL_TAG 100
- (id)init
{
    self = [super init];
    if (self) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
        _scrollView.clipsToBounds = YES;
        _scrollView.backgroundColor = [UIColor grayColor];
//        textLabel.text = @"12312312312";
        textLabel.tag  = ATTACH_READER_LABEL_TAG;
        textLabel.numberOfLines = 0;
        textLabel.font = [UIFont systemFontOfSize:14];
        //textLabel.backgroundColor = [UIColor greenColor];
        [_scrollView addSubview:textLabel];
        [textLabel release];
        
        [self.view addSubview:_scrollView];
    }
    return  self;
    
}

- (void)dealloc
{
    [_fileInputStream release];
    [_scrollView release];
    [super dealloc];
}

- (void)loadAttachment:(Attachment *)attachment
{
//    NSLog(@"%@", [attachment getHexFilePath]);
    
//    NSData *fileContentData = [NSData dataWithContentsOfFile:[attachment getHexFilePath]];
//    NSError *error;
////    NSLog(@"%@", [NSString stringWithContentsOfFile:[attachment getHexFilePath] encoding:NSASCIIStringEncoding error:&error]);
//    //NSString *fileContent = [[NSString alloc] initWithBytes:(const char *)buffer length:attachment.attachmentSize encoding:NSUTF8StringEncoding];
//    UILabel *textLabel = (UILabel *)[_scrollView viewWithTag:ATTACH_READER_LABEL_TAG];
//    textLabel.text = [NSString stringWithContentsOfFile:[attachment getHexFilePath] encoding:NSASCIIStringEncoding error:&error];
//    //NSLog(@"%@", [error localizedDescription]);
//    
//    return;
////    return;
    _fileInputStream = [NSInputStream inputStreamWithFileAtPath:[attachment getHexFilePath]];
    [_fileInputStream open];
    attachment.attachmentSize = 10;
    char *buffer = (char *)malloc(attachment.attachmentSize + 1);
    [StreamPeer readBytesWithInStream:_fileInputStream ptr:(UInt8 *)buffer maxLength:attachment.attachmentSize];
    
    buffer[attachment.attachmentSize + 1] = '\0';
    
    UILabel *textLabel = (UILabel *)[_scrollView viewWithTag:ATTACH_READER_LABEL_TAG];
    assert(nil != textLabel);
    NSString *fileContent = [[NSString alloc] initWithBytes:(const char *)buffer length:attachment.attachmentSize encoding:NSUTF8StringEncoding];
    textLabel.text = fileContent;
    NSLog(@"%@",fileContent);

    free(buffer);
    [fileContent release];
    buffer = NULL;
    
    [_fileInputStream close];
}
@end

